package com.zhn.evsi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhn.evsi.client.WalletClient;
import com.zhn.evsi.common.RedisCache;
import com.zhn.evsi.domain.dto.evsi.EvsiCharacterWalletJournalDTO;
import com.zhn.evsi.domain.entity.evsi.EvsiAuthToken;
import com.zhn.evsi.domain.entity.evsi.EvsiCharacterWalletJournal;
import com.zhn.evsi.mapper.EvsiCharacterWalletJournalMapper;
import com.zhn.evsi.service.IEvsiCharacterWalletJournalService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class EvsiCharacterWalletJournalServiceImpl extends ServiceImpl<EvsiCharacterWalletJournalMapper, EvsiCharacterWalletJournal> implements IEvsiCharacterWalletJournalService {


    @Resource
    private RedisCache redisCache;

    @Resource
    private WalletClient walletClient;

    // 定时任务查询钱包交易历史并持久化保存
    @Override
    public void journal(EvsiAuthToken authToken) {

        if (this.count(new LambdaQueryWrapper<EvsiCharacterWalletJournal>().eq(EvsiCharacterWalletJournal::getCharacterId, authToken.getCharacterID())) > 0) {
            this.remove(new LambdaQueryWrapper<EvsiCharacterWalletJournal>().eq(EvsiCharacterWalletJournal::getCharacterId, authToken.getCharacterID()));
        }

        // 查询钱包交易历史
        List<EvsiCharacterWalletJournalDTO> characterWalletJournalDTOList = new ArrayList<>();
        for (int i=1; i<100; i++) {
            List<EvsiCharacterWalletJournalDTO> journal = walletClient.journal(authToken.getCharacterID(), i);

            characterWalletJournalDTOList.addAll(journal);
            if (journal.size() < 1000) {
                break;
            }
        }

        // 将交易历史批量存储sql中
        List<EvsiCharacterWalletJournal> characterWalletJournalList = new ArrayList<>();
        characterWalletJournalDTOList.forEach(v -> {
            EvsiCharacterWalletJournal characterWalletJournal = EvsiCharacterWalletJournal.builder()
                    .characterId(authToken.getCharacterID())
                    .amount(v.getAmount())
                    .balance(v.getBalance())
                    .description(v.getDescription())
                    .refType(v.getRef_type())
                    .firstPartyId(v.getFirst_party_id())
                    .reason(v.getReason())
                    .id(v.getId())
                    .secondPartyId(v.getSecond_party_id())
                    .date(v.getDate())
                    .build();
            characterWalletJournalList.add(characterWalletJournal);
        });

        this.saveBatch(characterWalletJournalList);
    }
}
